import axios from 'axios';
import fetch from 'node-fetch';

export async function parseSourceImg(e, alsoGetAtAvatar = true, useOrigin = false) {
    let reply;
    if (alsoGetAtAvatar && e.at && !e.source && !e.reply_id && !e.img) {
        if (e.atBot) {
            e.img = [];
            e.img[0] = e.bot.avatar || `https://q1.qlogo.cn/g?b=qq&s=0&nk=${e.self_id}`;
        }
        if (e.at) {
            try {
                e.img = [await e.group.pickMember(e.at).getAvatarUrl()];
            } catch (error) {
                e.img = [`https://q1.qlogo.cn/g?b=qq&s=0&nk=${e.at}`];
            }
        }
    }
    if (e.source) {
        if (e.isGroup) {
            reply = (await e.group.getChatHistory(e.source.seq, 1)).pop()?.message;
        } else {
            reply = (await e.friend.getChatHistory(e.source.time, 1)).pop()?.message;
        }
    }
    else if (e.reply_id) {
        reply = (await e.getReply(e.reply_id)).message;
    }
    if (reply) {
        let i = [];
        for (const val of reply) {
            if (val.type == 'image') {
                i.push(val.url);
            }
            if (val.type == 'file') {
                e.reply('不支持消息中的文件，请将该文件以图片发送...', true);
                return;
            }
        }
        if (Boolean(i.length)) e.img = i;
    }
    return e.img;
}

export async function url2Base64(url, isReturnBuffer = false) {
    try {
        const response = await axios.get(url, {
            responseType: 'arraybuffer',
            timeout: 60000, // 设置超时时间为60秒
        });

        const contentLength = response.headers?.['content-length'] || response.headers?.get('size');
        const maxSizeInBytes = 10 * 1024 * 1024; // 10MB in bytes

        if (contentLength && parseInt(contentLength) > maxSizeInBytes) {
            console.error('[皮皮插件]图片大小超过10MB，请使用大小合适的图片');
            return null;
        }
        if (isReturnBuffer) return Buffer.from(response.data, 'binary');

        return Buffer.from(response.data, 'binary').toString('base64');
    } catch (error) {
        console.error(`[皮皮插件]下载引用图片错误，可能是图片链接已失效，使用的图片链接：\n` + url);
        return null;
    }
}

export async function uploadImage(imgUrl, domain) {
    if (!domain) {
        throw new Error('未配置图片服务器域名，请先设置域名');
    }

    try {
        const response = await fetch(imgUrl, { timeout: 30000 });
        if (!response.ok) {
            throw new Error(`获取图片失败: ${response.status} ${response.statusText}`);
        }
        const imgBuffer = Buffer.from(await response.arrayBuffer());
        const boundary = '----WebKitFormBoundary' + Math.random().toString(36).slice(2);
        const formBody = [
            `--${boundary}`,
            'Content-Disposition: form-data; name="file"; filename="image.jpg"',
            'Content-Type: image/jpeg',
            '',
            imgBuffer.toString('binary'),
            `--${boundary}--`,
            '',
        ].join('\r\n');

        const uploadResponse = await fetch(`${domain}/upload.php`, {
            method: 'POST',
            body: Buffer.from(formBody, 'binary'),
            headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` },
            timeout: 30000,
        });

        if (!uploadResponse.ok) {
            throw new Error(`上传失败: ${uploadResponse.status} ${uploadResponse.statusText}`);
        }

        const uploadResult = await uploadResponse.json();
        if (uploadResult.code !== 200) {
            throw new Error(uploadResult.msg);
        }

        return uploadResult.img.replace(/([^:])\/+/g, '$1/');
    } catch (error) {
        throw error;
    }
}